package cn.dengta.webapp.trade.model;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;

import cn.dengta.common.context.I18N;
import cn.dengta.common.model.TimeInterval;
import cn.dengta.common.model.ValueProxy;
import cn.dengta.context.model.BaseI18nKey;
import cn.dengta.context.model.LabelI18nProxy;
import lombok.Getter;
import me.codeplayer.util.EasyDate;

@Getter
public enum GoddessWeekType implements LabelI18nProxy<GoddessWeekType, Integer> {
	ONE(1, BaseI18nKey.WEEK),
	TWO(2, BaseI18nKey.WEEK),
	THREE(3, BaseI18nKey.WEEK),
	FOUR(4, BaseI18nKey.WEEK),
	;

	final ValueProxy<GoddessWeekType, Integer> proxy;


	GoddessWeekType(Integer value, String label) {
		this.proxy = new ValueProxy<>(this, value, label);
	}

	@Override
	public ValueProxy<GoddessWeekType, Integer> getProxy() {
		return proxy;
	}



	public static GoddessWeekType of(Integer type) {
		return ONE.getValueOf(type);
	}

	public static GoddessWeekType current(long now) {
		final EasyDate easyDate = new EasyDate(now);
		int week = BigDecimal.valueOf(easyDate.getDay()).divide(BigDecimal.valueOf(7), RoundingMode.UP).intValue();
		if (week > 4) {
			week = 4;
		}
		return of(week);
	}

	/** 计算发放的权益时间范围 */
	public static TimeInterval calc(long now, int remainDays) {
		final GoddessWeekType current = current(now);
		Date begin = EasyDate.beginOf(new Date(now), Calendar.DAY_OF_MONTH);
		final EasyDate beginDate = new EasyDate(begin);
		final EasyDate nowDate = new EasyDate(now);
		beginDate.addDay(7 + (current.getLastDayOfMonth(now) - nowDate.getDay()) + remainDays);
		return new TimeInterval(begin, beginDate.endOf(Calendar.DAY_OF_MONTH).toDate());
	}

	/** 计算周期 */
	public TimeInterval calcWeek(long now) {
		final EasyDate easyDate = new EasyDate(now);
		easyDate.setDay((getValue() - 1) * 7 + 1);
		Date begin = EasyDate.beginOf(easyDate.toDate(), Calendar.DAY_OF_MONTH);
		final EasyDate beginDate = new EasyDate(begin);
		if (this == FOUR) {
			beginDate.setDay(getLastDayOfMonth(now));
		} else {
			beginDate.addDay(6);
		}
		return new TimeInterval(begin, beginDate.endOf(Calendar.DAY_OF_MONTH).toDate());
	}

	public int getLastDayOfMonth(long now) {
		if (this == FOUR) {
			return new EasyDate(now).getLastDayOfMonth();
		} else {
			return getValue() * 7;
		}
	}

	@Override
	public String getLabel() {
		return getValue() + I18N.msg(getProxy().getLabel());
	}
}
